<script setup lang="ts">
import { ref, onMounted, reactive } from 'vue';
import { showToast, getCurrentInstance, showLoading, navigateTo } from '@tarojs/taro';
import { fileNameForUploadFile, uploadImageFile } from '/@/utils/file';
import {
  QUERY_APP_WO_DELIVER_DETAIL,
  CONFIRM_APP_TASK,
} from '/@/api/modules/deliver/app-wo-deliver';

/**
 * 获取路由参数
 */
const params = getCurrentInstance().router?.params as { id: string };
const state = reactive<{
  /**
   * 工单信息
   */
  info: AppWoDeliver.Dto;
}>({
  info: {},
});

/**
 * 签名的url数据
 */
const signUrl = ref('');
/**
 * 确认签名
 * @param canvas
 * @param data
 */
function confirm(canvas: any, data: any) {
  console.log('图片地址', canvas, data);
  if (data === '') {
    showToast({ title: '请填写签名!', icon: 'error' });
    return false;
  }
  signUrl.value = canvas.toDataURL('image/png');
  const newUrl = signUrl.value.replace('data:image/png;base64,', '');
  const suffix = '.jpg'; //文件名后缀
  const fileName = fileNameForUploadFile(suffix);
  console.log('newUrl:', newUrl);
  uploadImageFile(
    '',
    fileName,
    fileName,
    'schedule',
    (url: string) => {
      formState.woDeliverEventDto.woDeliverEventFileDto?.push({
        fileType: 1,
        fileUrl: url,
        fileName: fileName,
      } as AppWoDeliver.eventFileDto);
      confirmAppTask();
    },
    '2',
    newUrl,
  );
}

/**
 * 确认运送工单
 */
function confirmAppTask() {
  showLoading();
  formState.woDeliverDto.id = params.id;
  formState.woDeliverEventDto.workOrderId = params.id;
  CONFIRM_APP_TASK(formState).then(() => {
    formState.woDeliverEventDto = {
      workOrderId: '',
      woDeliverEventFileDto: [],
    };
    formState.woDeliverDto = {
      id: '',
    };
    navigateTo({
      url: `/pages/deliver/sign-success/index?id=${params.id}`,
    });
  });
}

const formState = reactive<{
  woDeliverEventDto: AppWoDeliver.eventDto;
  woDeliverDto: AppWoDeliver.Dto;
}>({
  woDeliverEventDto: {
    workOrderId: '',
    woDeliverEventFileDto: [],
  },
  woDeliverDto: {
    id: '',
  },
});

/**
 * 重置签名
 */
function clear() {
  signUrl.value = '';
}
/**
 * @function 获取工单详情
 */
function getDetail() {
  showLoading();
  QUERY_APP_WO_DELIVER_DETAIL({ id: params.id }).then((res) => {
    state.info = res.woDeliverDto;
  });
}

onMounted(() => {
  getDetail();
});
</script>

<template>
  <view class="deliver-sign app-page--1">
    <app-navbar title="手写签名" />
    <scroll-view class="app-page__wrapper" :scroll-y="true" :lower-threshold="100">
      <view class="deliver-sign__wrapper">
        <nut-signature
          :lineWidth="4"
          @confirm="confirm"
          @clear="clear"
          class="deliver-sign__signature"
        ></nut-signature>
      </view>
    </scroll-view>
  </view>
</template>

<style lang="scss" scoped>
@import './index.scss';
</style>
